package com.huawei.translate.notification.service;

import com.google.gson.Gson;
import com.huawei.translate.notification.EmailEntity;
import com.huawei.translate.notification.model.EmailHistory;
import com.huawei.translate.notification.repository.EmailHistoryRepository;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class EmailSender implements Isender {

    private Logger logger = Logger.getLogger(EmailSender.class);

    @Autowired
    private EmailHistoryRepository emailHistoryRepository;

    @Autowired
    private JavaMailSender javaMailSender;

    private ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    private Gson gson = new Gson();

    @Override
    public void send(EmailHistory email) {
        EmailEntity emailEntity = gson.fromJson(email.getContent(), EmailEntity.class);
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        try {
            helper.setFrom(emailEntity.getFrom());
            helper.setTo(emailEntity.getTo().split(";"));
            helper.setSubject(emailEntity.getSubject());
            helper.setText(emailEntity.getContent(), true);
        } catch (MessagingException e) {
            logger.error("SendEmail Happened Error:" + emailEntity.getContent());
            e.printStackTrace();
            logger.error(e.getMessage());
        }

        cachedThreadPool.submit(() -> {
            try {
                javaMailSender.send(message);
                email.setStatus(1);
                emailHistoryRepository.save(email);
            } catch (Exception ex) {
                logger.error("Send Email happened Error when send email" + emailEntity.getContent());
                ex.printStackTrace();
                logger.error(ex.getMessage());
            }
        });
    }
}
